package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Employee;

import cn.wolfcode.crm.query.JsonResult;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/loginUser")
    @ResponseBody
    public JsonResult login(String username, String password, HttpSession session) {
      /*  // 往 session 中存入查询出来员工对象
        UserContext.setCurrentEmployee(employee);
        //session.setAttribute("EMPLOYEE_IN_SESSION",employee);
        // 如果不是管理员,则把员工相关权限存入 session 中
        if (!employee.isAdmin()) {
            UserContext.setExpression(permissionService.queryByEmployeeId(employee.getId()));
            //session.setAttribute("EXPRESS_IN_SESSION",permissionService.queryByEmployeeId(employee.getId()));
            return new JsonResult(true, "登陆成功");
        } else {
            return new JsonResult(false, "登陆失败");
        }*/

        // 获取 subject 主体对象,判断登录状态
        try {
        Subject subject = SecurityUtils.getSubject();
        //System.out.println("认证状态:" + subject.isAuthenticated());
        //System.out.println(subject.toString());
        // 创建令牌(携带登陆用户的用户名和密码),对密码进行加密
        Md5Hash md5Hash = new Md5Hash(password,username);
        UsernamePasswordToken token = new UsernamePasswordToken(username,md5Hash.toString());
        // 执行登陆操作
        subject.login(token);
        // 判断账号是否被冻结
        Employee employee=(Employee)subject.getPrincipal();
        if (!employee.isStatus()){
            return new JsonResult("账号被冻结");
        }
        //System.out.println("认证状态:" + subject.isAuthenticated());
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return new JsonResult("账号或密码错误");
        }
        return new JsonResult(true,"登陆成功");
    }
}
